/**
 * 行政机构选择器
 */
import React from 'react';
import { Spin, TreeSelect } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { fetchDutyListByOrganization } from '../service';

const filterDuties = (tree, disabledKeys = []) =>
    tree.map(({ dutyAlias, dutyCode }) => ({
        title: dutyAlias,
        value: dutyCode,
        key: dutyCode,
        disabled: disabledKeys.includes(dutyCode)
    }));

const filterTree = (tree, disabledKeys = []) =>
    tree.map(({ children, organizationName, organizationCode, duties, ...props }) => {
        if ((children && children.length > 0) || (duties && duties.length > 0)) {
            return {
                children: [...filterTree(children, disabledKeys), ...filterDuties(duties, disabledKeys)],
                title: organizationName,
                value: organizationCode,
                key: organizationCode,
                selectable: false,
                disabled: disabledKeys.includes(organizationCode),
                ...props
            };
        }
        return {
            children: '',
            title: organizationName,
            value: organizationCode,
            key: organizationCode,
            // selectable: !!(!children?.length && !duties?.length),
            selectable: false,
            disabled: disabledKeys.includes(organizationCode),
            ...props
        };
    });

const DutyTreeSelect = React.forwardRef(
    ({ value, onChange, requestParams, style, disabledKeys, permissionsLimit = false, ...rest }, ref) => {
        const { data, loading } = useRequest(
            () =>
                fetchDutyListByOrganization({
                    organizationPermissions: permissionsLimit ? 1 : 0,
                    showTreeFlag: 1,
                    ...requestParams
                }),
            {
                cacheKey: 'dutyTreeSelect',
                ...defaultFormatResult
            }
        );

        const treeData = React.useMemo(() => {
            const finalData = Array.isArray(data) ? data : [];
            return filterTree(finalData, disabledKeys);
        }, [data, disabledKeys]);

        const finalValue = value === '' ? undefined : value;

        return (
            <Spin spinning={loading}>
                <TreeSelect
                    ref={ref}
                    value={finalValue}
                    onChange={onChange}
                    treeData={treeData}
                    allowClear
                    placeholder="请选择岗位"
                    showSearch
                    treeNodeFilterProp="title"
                    treeDefaultExpandAll
                    style={{ width: 170, ...style }}
                    dropdownStyle={{ maxHeight: 250, overflowY: 'visible' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    {...rest}
                />
            </Spin>
        );
    }
);

export default DutyTreeSelect;
